/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.sql.ResultSet;
import pojo.KhachHangPOJO;
import util.MySQLDataAccessHelper;

/**
 *
 * @author NhatHuy
 */
public class KhachHangDAO {
    
    /**
     * Phương thức thêm khách hàng.
     */
    public static boolean themKhachHang(KhachHangPOJO kh){
        boolean kq = false;
        try{
            String sql = "INSERT INTO khachhang(TenDangNhap,MatKhau,HoTen,DiaChi,Email,MaLoaiTaiKhoan) VALUES ('%s',MD5('%s'),'%s','%s','%s',2)";
            sql = String.format(sql, kh.getTenDangNhap(),kh.getMatKhau(),kh.getHoTen(),kh.getDiaChi(),kh.getEmail());
            MySQLDataAccessHelper helper = new MySQLDataAccessHelper();
            helper.open();
            int n = helper.executeUpdate(sql);
            if (n == 1){
                kq = true;
            }else{
                kq = false;
            }
            helper.close();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        return kq;
    }
    
     /**
     * Phương thức đăng nhập.
     */
    public static boolean dangNhap(String tenDangNhap, String matKhau){
        boolean kq = false;
        try{
            String sql = "SELECT COUNT(*) FROM KHACHHANG WHERE TenDangNhap='"+tenDangNhap+"' AND";
            sql += " MatKhau=MD5('"+matKhau+"')";
            
            MySQLDataAccessHelper helper = new MySQLDataAccessHelper();
            helper.open();
            ResultSet rs = helper.executeQuery(sql);
            //Đếm số dòng.
            rs.next();
            int n = rs.getInt(1);
            if (n == 1){
                kq = true;
            }else{
                kq = false;
            }
            helper.close();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        return kq;
    }   
    
    /**
     * Phương thức lấy thông tin khách hàng theo tên đăng nhập.
     */
    public static KhachHangPOJO layThongTin(String tenDangNhap){
        KhachHangPOJO kh = new KhachHangPOJO();
        try{
            String sql = "SELECT * FROM KHACHHANG WHERE TenDangNhap='"+tenDangNhap+"'";
            
            MySQLDataAccessHelper helper = new MySQLDataAccessHelper();
            helper.open();
            ResultSet rs = helper.executeQuery(sql);
            while (rs.next()){
                kh.setTenDangNhap(rs.getString("TenDangNhap"));
                kh.setMatKhau(rs.getString("MatKhau"));
                kh.setHoTen(rs.getString("HoTen"));
                kh.setDiaChi(rs.getString("DiaChi"));
                kh.setEmail(rs.getString("Email"));
                kh.setMaLoaiTaiKhoan(rs.getInt("MaLoaiTaiKhoan"));
            }
            helper.close();
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        return kh;
    }   
}
